<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HashRouter 实现原理</title>
    <style>
        #result{
            width: 400px;
            height: 300px;
            border:solid 1px #666;
        }
    </style>
</head>
<body>
    <a href="/home">Home</a>
    <a href="/about">About</a>
    <hr>
    <div id="result"></div>

    <script>
        //获取 result 元素
        let result = document.querySelector('#result');
        //获取 a 元素
        let links = document.querySelectorAll('a');

        //遍历 links
        links.forEach(item => {
            //绑定事件
            item.onclick = function(e){
                //阻止默认行为
                e.preventDefault();
                //获取当前链接的 href 属性
                let href = this.href;
                //
                history.pushState({id: 100}, '', href);

                //根据 url 的路径显示不同内容
                //获取页面 url 的路径
                let pathname = location.pathname;
                //判断
                switch(pathname){
                    case '/home':
                        result.innerHTML = 'Home Home Home';
                        break;
                    case '/about':
                        result.innerHTML = 'About About About';
                        break;
                    default: 
                        result.innerHTML = '404 Not Found';
                }
            }
        });

        //全局事件 popstate       后退历史时 触发的事件
        window.addEventListener('popstate', () => {
            //获取页面 url 的路径
            let pathname = location.pathname;
            //判断
            switch(pathname){
                case '/home':
                    result.innerHTML = 'Home Home Home';
                    break;
                case '/about':
                    result.innerHTML = 'About About About';
                    break;
                default: 
                    result.innerHTML = '404 Not Found';
            }
        });
       

    </script>
</body>
</html>